package application

import (
	"gitee.com/yunduansing/gocommon/consul"
	"gitee.com/yunduansing/gocommon/grpc"
	"gitee.com/yunduansing/iristest/grpc/test"
	pb "gitee.com/yunduansing/iristest/proto/test"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/context"
	g "google.golang.org/grpc"
)

func Startup() (app *iris.Application)  {
	app=iris.Default()
	app.Use(Recover())
	RegisterConsulService()
	RegisterGrpc()
	return
}

func RegisterGrpc()  {
	go func() {
		server := g.NewServer()
		pb.RegisterTestServiceServer(server,test.TestService)
		grpc.RegisterGrpc("localhost:8500",server,8883,"localhost","iristestGrpc")

	}()
}

func RegisterConsulService()  {
	err:=consul.Register("localhost:8500","localhost",8881,"iristestWebApi","/health")
	if err!=nil{
		panic(err)
	}
}

func Recover() context.Handler {
	return func(c iris.Context) {
		defer func() {
			if r:=recover();r!=nil{
				c.JSON(iris.Map{
					"success": false,
					"msg":     errorToString(r),
					"data":    nil,
				})
				//终止当前接口
				c.StopExecution()

			}
		}()
		c.Next()
	}

}

// recover错误，转string
func errorToString(r interface{}) string {
	switch v := r.(type) {
	case error:
		return v.Error()
	default:
		return r.(string)
	}
}

